// pages/equipmentAdd/equipmentAdd.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //厂家id
    factoryId:'',
    //厂家名称
    factoryName:'',
    //厂家选择框
    showFactory:false,
    //厂家设备型号选择框
    showFactoryType:false,
    //厂家设备型号
    equipmentBaseId:'',
    //厂家设备型号显示的名称
    equipmentBaseName:'',
    //经销商id
    dealerId:null,
    //经销商名称
    dealerName:'',
    //经销商选择框
    showDealer:false,
    //客户id
    memberId:null,
    //客户名称
    memberName:'',
    //客户的类型
    memberOfType:null,
    //客户选择框
    showMember:false,
    //客户设备型号选择框
    showUserType:false,
    //客户设备型号
    memberTypeId:'',
    //客户设备型号的名称
    memberTypeName:'',
    memberTypeStr:'',
    //项目id
    projectId:null,
    //项目名称
    projectName:'',
    //项目选择框
    showProject:false,
    //提交按钮是否禁用
    disabled: false,
    //传参来的设备id
    equipmentId:null,
    //编辑时获取的设备信息
    editInfo:{},
    //设备的数据权限
    authDepart:[],
    //登录的客户信息
    userInfo:{},
    //显示上传组件
    showUpload:true,
    //图片
    headImg:'',
    //清洁面积/里程
    workAmount:null,
    //选择清洁单位
    showWorkUnit:false,
    workUnit:'㎡',
    workUnitStr:'㎡/小时',
    workUnitList:[
      {
        text:'㎡/小时',
        workUnit:'㎡'
      },{
        text:'km/小时',
        workUnit:'km'
      }
    ],
    //选择充电方式
    showCharge:false,
    chargeId:2,
    chargeName:'设备外充',
    chargeList:[
      {
        id:1,
        text:'蓄电池直充'
      },{
        id:2,
        text:'设备外充'
      }
    ],
    //是否是修改
    isEdit:false,  
    //是否是厂家从订单中绑定设备
    isfactoryBind:false,
    //是否是厂家从新订单中绑定设备
    isfactoryBindNew:false,
    //厂家从订单中绑定设备-传参来的信息
    factoryBind:null,
    //用户权限
    authority:null,
    //设备类型选择数据
    typeList:[],
    //一级分类列表
    typeOne:[],
    //设备类型选择框
    showType:false,
    //选择的设备类型id
    typeIds: [],
    //选择的设备类型名字
    typeNames: '',    
    //保洁供应方id
    cleaningSupplierId:null,
    //保洁供应方名称
    cleaningSupplierName:'',
    //保洁供应方选择框
    showCleaningSupplier:false,
    //搜索保洁供应方输入的值
    valueSearchCleaning:'',
    //保洁供应方项目id
    cleaningSupplierProjectId:null,
    //保洁供应方项目名称
    cleaningSupplierProjectName:'',
    //保洁供应方项目选择框
    showCleaningSupplierProject:false,
    //搜索保洁供应方项目输入的值
    valueSearchCleaningProject:'',
    //搜索客户输入的值
    valueSearchMember:'',
    //搜索项目输入的值
    valueSearchProject:'',  
    //所有权
    owner:'',
    //设备修改权
    editer:'',
    //大区id
    regionId:null,
    //大区名称
    regionName:'',
    //大区选择框
    showRegion:false,
    //搜索大区输入的值
    valueSearchRegion:'',    
    //避免表单重复提交
    code:null,
    //是否可编辑imei输入框
    isImeiEdit:false,
    //是否显示equipmentNo
    showEquipmentNo:true,
    //是否显示equipmentNo输入框
    showNo:false,
    //是否显示equipmentNo切换
    showNoSwitch:true,
    //业务类型选择框
    showBusinessType:false,
    //业务类型选择数据
    businessTypeList:[],
    //平台id
    myAppId:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    appIdCode: app.globalData.appId
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //console.log("||||||");
    //console.log(options);
    let user=app.globalData.userInfo;
    let equipmentNoSelf=app.globalData.equipmentNoSelf;
    let myAppId=app.globalData.myAppId;

    this.setData({
      userInfo: user,
      authority:app.globalData.authority,
      code:Base64.encode(new Date() + user.userName),
      myAppId:myAppId
    })

    //按平台处理业务类型选择数据
    if(myAppId==7){
      this.setData({
        businessTypeList:[{
          id:-1,
          text:'销售'
        },{
          id:6,
          text:'租赁'
        }]
      })
    }else{
      this.setData({
        businessTypeList:[{
          id:5,
          text:'存量改造'
        },{
          id:1,
          text:'销售'
        },{
          id:2,
          text:'租赁-授信'
        },{
          id:3,
          text:'租赁订单-非授信'
        },{
          id:4,
          text:'试机'
        }]
      })
    }

    //equipmentNo不显示：配置文件设置了不自动填写并且是客户
    if(!equipmentNoSelf && user.typeHandle==4){
      this.setData({
        showEquipmentNo:false
      })
    }

    //equipmentNo可自行填写：配置文件设置了，或是厂家
    if(equipmentNoSelf || user.typeHandle==2){
      this.setData({
        showNoSwitch:false,
        showNo:true
      })
    }

    //获取修改时传过来的设备id
    if(options.equipmentId){
      wx.setNavigationBarTitle({
        title: '修改设备'
      })

      this.setData({
        equipmentId: parseInt(options.equipmentId),
        showUpload:false,
        isEdit:true
      })

      //如果是编辑状态而且登录用户是客户，则无法编辑imei，
      //2022-12-6新增，独立经销商的一级部门可以编辑，只有独立小程序加了，战力没加    
      if((user.role.length) && (user.role.indexOf(54)!=-1) && (user.departObj[0].level==1)){
        this.setData({
          isImeiEdit: false
        })
      }else if(user.departObj[0].type==4){
        this.setData({
          isImeiEdit: true
        })
      }  

      //获取设备信息
      this.getEquipmentInfo();
    }else{
        //添加时
        //如果是天骏小程序，客户项目大区型号等初始化值
        if(app.globalData.myAppId==6){
            this.initProjectInfo();
        }
    }

    //厂家从订单中绑定设备-获取参数（原来）
    if(options.factoryBind){
      let obj=JSON.parse(options.factoryBind);
      console.log('厂家订单绑定-传参');
      console.log(obj);

      this.setData({
        factoryBind:obj,
        isfactoryBind:true,
        headImg: obj.pic,
        showUpload:false,
        memberId: obj.memberId,
        dealerId: obj.dealerId,
        memberTypeName:obj.equipmentName,
        //equipmentBaseName:obj.equipmentName,
        projectId:obj.projectId,
      });

      //根据设备型号查询相关信息
      this.findFactoryType();

      //查询项目fid
      if(obj.projectId){
        this.getProjectFid(obj.projectId);
      }
    }

    //厂家从订单中绑定设备-获取参数（新）
    if(options.factoryBindNew){
      let obj=JSON.parse(options.factoryBindNew);
      console.log('厂家新订单绑定-传参');
      console.log(obj);

      //处理清洁面积及单位
      let workAmount = 0;
      let workUnitStr="";
      let workUnit = "";
      if(obj.spu.efficiency != null){
        workAmount = obj.spu.efficiency.value;
        workUnit = obj.spu.efficiency.unit.split("/")[0];
        workUnitStr = obj.spu.efficiency.unit;
      }

      //处理设备类型
      let typeIds=[];
      if(obj.spu && obj.spu.categoryId && obj.spu.categoryId.length){
        typeIds=obj.spu.categoryId;
      }

      //处理设备类型显示名称
      let names=[];
      if(obj.spu && obj.spu.category && obj.spu.category.length){
        let typeNames=obj.spu.category;
        typeNames.forEach(item => {
          names.push(item.name);
        });
      }

      this.setData({
        factoryBind:obj,
        isfactoryBindNew:true,
        headImg: obj.spu.imgUrl,
        showUpload:false,
        memberId: obj.memberId,
        dealerId: obj.dealerId,
        orderNo:obj.orderNo,
        memberTypeName:obj.equipmentName,
        memberTypeId:obj.spu.id,
        equipmentBaseId:obj.sku.supplierId,
        equipmentBaseName:obj.sku.supplierType,
        projectId:obj.projectId,
        workAmount:workAmount,
        workUnit:workUnit,
        workUnitStr:workUnitStr,
        cleaningSupplierId:obj.cleaningSupplierId,
        cleaningSupplierProjectId:obj.cleaningSupplierProjectId,
        editerIds:obj.editerIds,
        ownerIds:obj.ownerIds,
        cleaningSupplierName:obj.cleaningSupplierName,
        cleaningSupplierProjectName:obj.cleaningSupplierProjectName,
        businessType:obj.businessType,
        typeIds:typeIds,
        typeNames:names.join(' - '),
        orderDetailId:obj.orderDetailId,
        orderDetailInedx:obj.orderDetailInedx,
        detailIndex:obj.detailIndex,
        //业务员
        salesman: obj.salesman
      })

    //   this.autoSelectRegion(obj.projectIdFid);
    //   //查询项目fid
    //   if(obj.projectId){
    //     this.getProjectFid(obj.projectId);
    //   }

        //查询大区，查询项目的父级并且是大区的，如果没有就取父级
        this.getRegion(obj);
    }
  },

  getRegion(obj){
    console.log("obj",obj)
    let param ={}
    //判断rid不等于空并且不等于0
    if(obj.projectRid != null && obj.projectRid !="" && obj.projectRid != 0){
      param={
        isAuth:true,
        className:'depart',
        data:{
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          searchAll:true,
          id:obj.projectRid,
          selectFields:["id","name"]
        }
      }
    }else{
      param={
        isAuth:true,
        className:'depart',
        data:{
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          searchAll:true,
          id:obj.projectIdFid,
          selectFields:["id","name"]
        }
      }
    }
    CommonService.goFindList(param).then(res=>{
      console.log(res);
      console.log("daq");
      let result=res.data.data.result[0];
      console.log(result);
      this.setData({
        regionId: result.id,
        regionName: result.name
      })
    }).catch((error) => {
    })
  },

  //获取设备信息
  getEquipmentInfo(){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        id:this.data.equipmentId,
        selectFields:['id','imei','equipmentNo','businessType','equipmentBaseName','equipmentAlias','typeArr','categoryArr',
        'regionId','region','projectId','project','memberTypeName','memberTypeId','memberType','iconUrl','workAmount',
        'workUnit','workSpeed','chargingMode','memberId','member','factoryId','factory','equipmentBaseId',
        'equipmentBase','dealerId','dealer','cleaningSupplierId','cleaningSupplier','cleaningSupplierProjectId',
        'cleaningSupplierProject','ownerIds','editerIds','oldImei',"orderNo","orderDetailInedx","orderDetailId","purchaseOrderId","isfactoryBindNew","detailIndex","centreId","centre","createDate","effectiveDate","renewalInfo","editImeiInfo"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let result=res.data.data.result[0];

        //处理业务类型显示名称
        if(result.businessType){
          let bList=this.data.businessTypeList;
          bList.forEach(item => {
            if (item.id==result.businessType){
              result.businessTypeName=item.text;
            }
          });
        }

        this.setData({
          editInfo: result
        })

        //编辑设备时获取各个字段的值
        this.getInputValue();
      }
    }).catch((error) => {
    })
  },

  //编辑设备时获取各个字段的值
  getInputValue(){
    let info=this.data.editInfo;

    console.log('修改设备信息回显');
    console.log(info);

    //客户设备型号
    let memberTypeStr='';
    //图片
    let headImg='';
    //清洁工作量（面积/里程）
    let workAmount=0;

    //处理客户设备型号
    if(info.memberTypeName){
      memberTypeStr=info.memberTypeName;
    }else if(info.memberType.length && info.memberType[0].name){
      memberTypeStr=info.memberType[0].name;
    }

    //处理图片
    if(info.iconUrl){
      headImg=info.iconUrl
    }else if(info.memberType.length && info.memberType[0].iconUrl){
      headImg=info.memberType[0].iconUrl
    }

    //去掉图片url的乱码
    if(headImg && headImg.indexOf("?")!=-1){
      let index = headImg.indexOf("?");
      if (index != -1) {
        headImg = headImg.substring(0, index);
      }
    }

    //处理清洁工作量
    if(info.workAmount){
      workAmount=info.workAmount;
    }else if(info.cleanArea){
      workAmount=info.cleanArea;
    }else if(info.memberType.length && info.memberType[0].cleanArea){
      workAmount=info.memberType[0].cleanArea;
    }

    //处理设备类型名称
    let names=[];
    if(info.categoryArr && info.categoryArr.length){
      let typeNames=info.categoryArr;
      typeNames.forEach(item => {
        names.push(item.name);
      });
    }

    //处理所有权
    if(info.ownerIds && info.ownerIds.length){
      if(info.ownerIds[0]==info.memberId){
        this.setData({
          owner: '1'
        })
      }else{
        this.setData({
          owner: '2'
        })
      }
    }

    //处理修改权
    if(info.editerIds && info.editerIds.length){
      let editerArr=[];
      if(info.editerIds.indexOf(info.memberId)!=-1){
        editerArr.push('1');
      }
      if(info.editerIds.indexOf(info.cleaningSupplierId)!=-1){
        editerArr.push('2');
      }
      this.setData({
        editer: editerArr
      })
    }

    //如果是从订单绑定的设备需要修改的时候，equipmentBaseName用带过来的值
    let equipmentBaseStr = "";
    if (this.data.factoryBindNew) {
        equipmentBaseStr = info.equipmentBaseName;
    } else {
        equipmentBaseStr = info.equipmentBase.length ? info.equipmentBase[0].typeCode : '';
    }

    this.setData({
      imei:info.imei,
			projectId:info.projectId ? info.projectId : '',
      projectName:info.project.length ? info.project[0].name : '',
      headImg:headImg ? headImg : '/images/nothing.jpg',
      memberTypeStr:memberTypeStr,
      memberTypeName:memberTypeStr,
      workAmount:workAmount,
      memberTypeId:info.memberTypeId ? info.memberTypeId : null,
      equipmentBaseId:info.equipmentBaseId ? info.equipmentBaseId : '',
      equipmentBaseName:equipmentBaseStr,
      memberId:info.memberId?info.memberId:'',
      memberName:info.member.length?info.member[0].name:'',
      dealerId:info.dealerId?info.dealerId:'',
      dealerName:info.dealer.length?info.dealer[0].name:'',
      workUnit:info.workUnit ? info.workUnit : '',
      workUnitStr:info.workUnit ? info.workUnit+'/小时' : '',
      typeIds:info.typeArr,
      typeNames:names.join(' - '),
      factoryId:info.factoryId,
      cleaningSupplierId:info.cleaningSupplierId ? info.cleaningSupplierId : null,
      cleaningSupplierName:info.cleaningSupplier.length ? info.cleaningSupplier[0].name : '',
      cleaningSupplierProjectId:info.cleaningSupplierProjectId ? info.cleaningSupplierProjectId : null,
      cleaningSupplierProjectName:info.cleaningSupplierProject.length ? info.cleaningSupplierProject[0].name : '',
      regionId:info.regionId ? info.regionId : null,
      regionName:info.region.length ? info.region[0].name : '',
      regionObj:info.region ? info.region : null,
      businessType:info.businessType ? info.businessType : null,
      orderNo:info.orderNo,
      orderDetailId:info.orderDetailId,
      orderDetailInedx : info.orderDetailInedx,
      purchaseOrderId : info.purchaseOrderId,
      isfactoryBindNew:info.isfactoryBindNew,
      detailIndex:info.detailIndex
		})
  },

  //检测数组中是否含有某个值
  isAddDepart(arr,str){
    if(arr.length){
      return arr.every(item=>{
        return item!=str;
      });
    }else{
      return true;
    }
  },

  //表单点击确认添加设备
  onConfirmAdd(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let td=this.data;
    //console.log("td---------------------------");
    //console.log(td);
    let user=app.globalData.userInfo;
    let authority = td.authority;
    let pro=e.detail.value;
    let showNo=td.showNo;

    let imei=pro.imei.trim();
    let equipmentAlias=pro.equipmentAlias.trim();

    let equipmentNo='';

    if(showNo){
      //如果允许输入equipmentNo
      equipmentNo=pro.equipmentNo.trim();
    }else{
      //之前的设备equipmentNo不变；新加的设备equipmentNo自动生成，时间戳+imei后六位
      if(td.isEdit){
        equipmentNo=td.editInfo.equipmentNo;
      }else{
        let dates=(util.timeFormatDay(new Date())).replaceAll('-','');
        let last6=imei.substring(imei.length-6);
        equipmentNo=dates + last6;
      }
    }

    //清洁面积/里程
    let workAmount=pro.workAmount.trim();

    //最大工作速度
    let workSpeed=null;
    if(!td.isfactoryBindNew){
      workSpeed=pro.workSpeed.trim();      
    }
    
    //客户名称
    let memberName='';
    //合伙人名称
    let partnerName='';

    //非空验证
    if(!this.formNotEmpty(imei,'imeiMessage','请输入物联网编码')){
      return;
    }

    if(showNo){
      if(!this.formNotEmpty(equipmentNo,'equipmentNoMessage','请输入设备编码')){
        return;
      }
    }

    if(!this.formNotEmpty(workAmount,'workAmountMessage','请输入清洁面积/里程')){
      return;
    }
    if(!this.formNotEmpty(td.workUnitStr,'workUnitMessage','请选择单位')){
      return;
    }

    //验证imei，equipmentNo，设备别名的重复性
    let editImei=td.imei;
    let editAlias=td.editInfo.equipmentAlias;
    let editNo=td.editInfo.equipmentNo;

    let flagImei=true;
    let flagAlias=true;
    let flagNo=true;

    let promiseArr=[];

    if(td.isEdit && (editImei==imei)){
    }else{
      flagImei=this.isExist(imei).then(value =>{
        if(value){
          this.setData({
            imeiMessage: '此编码已绑定设备',
            disabled:true
          })
        }
        return !value;
      });
    }

    if(td.isEdit && (editAlias==equipmentAlias)){
    }else{
      if(equipmentAlias){
        flagAlias=this.isExistAlias(equipmentAlias).then(value =>{
          if(value){
            this.setData({
              equipmentAliasMessage: '设备名称重复',
              disabled:true
            })
          }
          return !value;
        });
      }
    }

    if(showNo){
      if(td.isEdit && (editNo==equipmentNo)){
      }else{
        flagNo=this.isExistNo(equipmentNo).then(value =>{
          if(value){
            this.setData({
              equipmentNoMessage: '设备编码重复',
              disabled:true
            })
          }
          return !value;
        });
      }
      promiseArr.push(flagNo);
    }

    //业务类型必填
    // let authority=this.data.authority;
    // if(authority.iot.equipmentList.businessType && (td.myAppId==3 || td.myAppId==7)){
    //   if(!td.businessType){
    //     Toast.fail('请选择业务类型');
    //     return;
    //   }
    // }

    promiseArr.push(flagImei,flagAlias);

    let memberId=null;
    let factoryId=null;
    let partnerId=null;
    let dealerId=null;

    //权限
    let authDepart=[];

    //如果是天骏小程序
    if(app.globalData.myAppId==6){
        //任何人绑设备都加入天骏的权限
        authDepart.push(1806);
        //业务类型全是存量改造
        td.businessType=5;
    }

    //如果是安装人员
    if(user.isIotInstaller==true){
      let partnerFlag=true;

      if(td.memberId){
        memberId=td.memberId;
        authDepart.push(memberId);

        //如果客户本身还是经销商
        if(td.memberOfType==7){
          dealerId=td.memberId;
        }

        //查询客户的合伙人
        partnerFlag=this.findPartner(memberId).then(value => {
          if(value){
            partnerId=value;
            authDepart.push(partnerId);
          }
          return true;
        });
      }
      promiseArr.push(partnerFlag);

      if(td.factoryId){
        factoryId=td.factoryId;
        authDepart.push(factoryId);
      }

    }else{
      //如果是客户
      if(user.typeHandle==4 && user.isIotInstaller!=true){
        if(td.memberId){
          memberId=td.memberId;
        }else{
          memberId=user.departObj[0].companyId;
        }
        authDepart.push(memberId,user.depart);

        if(user.departObj[0].partnerId){
          partnerId=user.departObj[0].partnerId;
          authDepart.push(partnerId);
        }

        //如果客户本身还是经销商
        if(user.departObj[0].type==7){
          dealerId=memberId;
        }

        if(td.factoryId){
          factoryId=td.factoryId;
          authDepart.push(factoryId);
        }

        //业务类型为存量改造
        if(!td.businessType){
            td.businessType=5;
        }
      }

      //如果是厂家
      if(user.typeHandle==2 && user.isIotInstaller!=true){
        if(!td.isfactoryBindNew){
          if(!this.formNotEmpty(workSpeed,'workSpeedMessage','请输入最大工作速度')){
            return;
          }
        }

        if(!td.equipmentBaseName){
          Toast.fail('请选择设备型号');
          this.setData({
            disabled:true
          })
          return;
        }

        let partnerFlag=true;

        factoryId=user.departObj[0].id;
        authDepart.push(factoryId);

        dealerId=td.dealerId;
        authDepart.push(dealerId);

        if(td.memberId){
          memberId=td.memberId;
          authDepart.push(memberId);

          //查询客户的合伙人
          partnerFlag=this.findPartner(memberId).then(value => {
            if(value){
              partnerId=value;
              authDepart.push(partnerId);
            }
            return true;
          });
        }
        promiseArr.push(partnerFlag);
      }

      //如果是经销商
      if(user.departObj[0].type==7 && user.isIotInstaller!=true){
        dealerId=user.departObj[0].id;
        if(dealerId){
          authDepart.push(dealerId);
        }

        partnerId=user.departObj[0].id;
        authDepart.push(partnerId);

        if(td.memberId){
          memberId=td.memberId;
          authDepart.push(memberId);
        }
        if(td.factoryId){
          factoryId=td.factoryId;
          authDepart.push(factoryId);
        }
      }
    }

    //项目id
    if(td.projectId){
      authDepart.push(td.projectId);
    }

    //大区id
    if(td.regionId){
      authDepart.push(td.regionId);
    }

    //清洁面积为数字
    if(workAmount!='' && workAmount!=null){
      if(!(/^\d+(\.\d+)?$/.test(workAmount))){
        this.setData({
          workAmountMessage: '清洁面积为数字',
          disabled: true
        });
        return;
      }
    }

    //工作速度为数字
    if(workSpeed!='' && workSpeed!=null){
      if((/(^\d*$)/.test(workSpeed))){
        workSpeed=parseInt(workSpeed);
      }else{
        this.setData({
          workSpeedMessage: '工作速度为整数',
          disabled: true
        });
        return;
      }
    }else{
      workSpeed=0;
    }  

    if(user.typeHandle==4 && user.isIotInstaller!=true){
      memberName=user.departObj[0].name;
    }else{
      memberName=td.memberName;
    }

    //将保洁供应方放入权限数组
    let cleaningSupplierId=null;
    if(td.cleaningSupplierId){
      cleaningSupplierId=td.cleaningSupplierId;
      authDepart.push(cleaningSupplierId);
    }else{
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        cleaningSupplierId=1806;
        authDepart.push(1806);
      }
    }

    if(td.cleaningSupplierProjectId){
      authDepart.push(td.cleaningSupplierProjectId);
    }

    //处理所有权和修改权
    let ownerIds=[],editerIds=[];
    if(td.owner){
      let owner=td.owner;
      if(owner=='1'){
        ownerIds.push(td.memberId);
        authDepart.push(td.memberId);
      }else{
        ownerIds.push(td.cleaningSupplierId);
        authDepart.push(td.cleaningSupplierId);
      }
    }else{
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        ownerIds.push(1806);
      }
    }

    if(td.editer){
      let editer=td.editer;
      if(editer.indexOf('1')!=-1){
        editerIds.push(td.memberId);
        authDepart.push(td.memberId);
      }
      if(editer.indexOf('2')!=-1){
        editerIds.push(td.cleaningSupplierId);
        authDepart.push(td.cleaningSupplierId);
      }
    }else{  
      //如果是天骏小程序
      if(app.globalData.myAppId==6){
        editerIds.push(1806);
      }
    } 

    if(this.data.factoryBind){
      //处理所有权
      if(td.ownerIds && td.ownerIds.length){
        ownerIds = td.ownerIds
      }
      //处理修改权
      if(td.editerIds && td.editerIds.length){
        editerIds = td.editerIds
      }
    }

    //处理oldImei
    let oldImei=td.editInfo.oldImei;
    if(td.isEdit && td.editInfo.imei!=imei){
      oldImei=td.editInfo.imei;
    }    

    //处理设备类型
    let typeArrs = [];
    if (td.typeIds.length) {
        typeArrs = [1].concat(td.typeIds);
        let typeSet = new Set(typeArrs);
        typeArrs = Array.from(typeSet);
    } else {
        Toast.fail('请选择设备类型');
        return;
    }


    Promise.all(promiseArr).then(value => {
      //查询合伙人名称
      if(partnerId){
        let partnerNameFlag=this.getDepartName(partnerId).then(value => {
          partnerName=value;
          return true;
        });
        promiseArr.push(partnerNameFlag);
      }

      //处理权限
      let arrSet=[];
      authDepart.forEach(item => {
        if (item!=null){
          arrSet.push(item);
        }
      });
      arrSet=new Set(arrSet);
      authDepart=Array.from(arrSet);

      //添加客户设备型号  added  by 毕研帅   2022-05-06
        if (td.isfactoryBindNew) {
            if (td.memberTypeName != null) {
                memberTypeName = td.memberTypeName.trim();
            }
        }

	    //客户设备型号
      let memberTypeName = pro.memberTypeName.trim();
      if(!memberTypeName){
        if(user.typeHandle == 2){
          //厂家编辑时，如果客户型号为空，取厂家型号（为了导报表时有数据）
          memberTypeName=td.equipmentBaseName;
        }else{
          Toast.fail('请输入设备型号');
          return;
        }
      }

      //客户必填
        if (authority.iot.equipmentList.member) {
            if (!memberId) {
                Toast.fail('请选择所属甲方公司');
                return;
            }
        }

        //项目必填
        if (authority.iot.equipmentList.project) {
            if (!td.projectId) {
                Toast.fail('请选择所属项目');
                return;
            }
        }

      Promise.all(promiseArr).then(value => {
        let passed=value.every(val=>{
          return val;
        });

        if(passed){
          //处理搜索词
          let searchKeyArr=[imei,equipmentNo,equipmentAlias,memberTypeName,memberName,td.projectName,td.factoryName,partnerName,td.regionName,td.editInfo.self_fName,td.cleaningSupplierName,td.cleaningSupplierProjectName];
          let searchKey=util.arrayRepeatEmpty(searchKeyArr);

          //处理权限(去掉空值和重复)
          let dataAuthorityArrNew=[];
          authDepart.forEach(item => {
            if(item){
                dataAuthorityArrNew.push(item);
            }
          });
          let dataAuthoritySet=new Set(dataAuthorityArrNew);
          dataAuthorityArrNew=Array.from(dataAuthoritySet);

          //处理续费时间 
          let effectiveDate=null,
              renewalInfo=null,
              isSaveEffective=false;

          if(td.editInfo.effectiveDate && td.editInfo.renewalInfo){
            //已存过的不用再操作了
            isSaveEffective=true;
          }else{
            //获取创建日期
            let createDate=td.editInfo.createDate;
            if(!createDate){
              createDate=util.timeFormat(new Date());
            }
          
            //下一年
            let years=createDate.substring(0,4);
            let others=createDate.substring(4);
            let nextYear=Number(years)+1;

            //有效时间：创建日期的下一年（这里传字符串，存入数据库才是Date类型）
            effectiveDate=nextYear+others;

            //有效时间信息
            renewalInfo={
              //创建时间~有效时间
              date: createDate+'~'+effectiveDate,
              //当前时间（这里传Date类型，存入数据库是TZ格式的字符串，这个字段后期不用）
              renewalInfoDate: new Date(),
              //操作人员
              renewalInfoUser:{
                id: user.id,
                name: user.userName
              }
            }
          }

          let parameter={
            className:'equipment',
            data:{
              requestToken:this.data.code,
              id:td.equipmentId,
              //物联网IMEI
              imei:imei,
              //设备编号
              equipmentNo:equipmentNo,
              //速度
              workSpeed:workSpeed,
              //客户id
              memberId:memberId,
              //客户设备型号ID
              memberTypeId:td.memberTypeId || td.equipmentBaseId,
              //客户设备型号名称
              memberTypeName:memberTypeName || td.equipmentBaseName,
              //项目
              projectId:td.projectId,
              //大区
              regionId: td.regionId ? td.regionId : memberId,
              //大区名字
              region: td.regionName ? td.regionName : td.memberName,
              //图片
              iconUrl:td.headImg,
              //清洁工作量
              workAmount:Number(workAmount),
              //清洁单位
              workUnit:td.workUnit,
              //厂家id
              factoryId:factoryId,
              //厂家型号
              equipmentBaseId:td.equipmentBaseId,
              //厂家型号名称
              equipmentBaseName:td.equipmentBaseName,
              //经销商ID
              dealerId:dealerId,
              //合伙人id
              partnerId:partnerId,
              //充电方式
              chargingMode:td.chargeId,
              //保洁供应方
              cleaningSupplierId:cleaningSupplierId,
              //保洁供应方项目
              cleaningSupplierProjectId:td.cleaningSupplierProjectId,
              //所有权
              ownerIds:ownerIds,
              //修改权
              editerIds:editerIds,
              //权限
              dataAuthority:{
                depart:dataAuthorityArrNew,
                role:['iot_admin','admin','data_admin']
              },
              isVectorMotor:td.editInfo.isVectorMotor,
              searchKey:searchKey,
              typeArr:typeArrs,
              //设备别名
              equipmentAlias:equipmentAlias,
              //修改前的imei
              oldImei:oldImei,
              //区分什么业务类型的设备1.销售生成采购订单，2.租赁生成采购订单-授信,3.租赁生成采购订单-非授信,4.试机订单生产采购订单
              businessType:td.businessType,
              appId: [app.globalData.myAppId]
            }
          }

          if(!td.isEdit){
            //创建人
            parameter.data.createUser=user.id;
          }

          //中心
          if(td.editInfo.centreId){
            parameter.data.centreId=td.editInfo.centreId;
            parameter.data.centre=td.editInfo.centre;           
          }

          //续费有效期
          if(!isSaveEffective){
            parameter.data.effectiveDate=effectiveDate;
            parameter.data.renewalInfo=[renewalInfo];
          }

          //added  by 毕研帅  2022-04-19 18:04
          //系统下单把一下信息存入设备表，做修改用
          if(td.isfactoryBindNew != null && td.isfactoryBindNew && parameter.data.id == null){
            console.log("====");
            parameter.data.orderNo=td.orderNo;
            parameter.data.orderDetailId = td.orderDetailId;
            parameter.data.orderDetailInedx = td.orderDetailInedx;
            parameter.data.purchaseOrderId = this.data.factoryBind.orderId;
            parameter.data.isfactoryBindNew = td.isfactoryBindNew;
            parameter.data.detailIndex = td.detailIndex;
          }          

        //秦海文2023年2月17日添加
        let oldImeiQ=parameter.data.oldImei;

        //修改imei时保存修改记录，方便维护人员查询（登录人员、时间、编码、客户、项目）
        if(td.isEdit && td.editInfo.imei!=imei){
            let editImeiInfo=td.editInfo.editImeiInfo || [];
            editImeiInfo.push({
              editTime: util.timeFormat(new Date()),
              userId: user.id,
              userName: user.userName,
              imei: imei,
              oldImei: oldImei,
              member: td.memberName,
              memberId: td.memberId,
              project: td.projectName,
              projectId: td.projectId
            }); 
            parameter.data.editImeiInfo=editImeiInfo;
          }

          //厂家从订单绑设备保存业务员
          if(!td.isEdit && td.isfactoryBindNew && td.salesman){
            parameter.data.salesman=td.salesman;
          }

        //   console.log('###添加设备表单提交###');
        //   console.log(parameter.data);
        //   return;

          //避免表单重复提交
          Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '数据提交中...'
          });

          CommonService.goSave(parameter).then(res=>{
            Toast.clear();
            this.setData({
              disabled:false
            })

            if (res.statusCode == 200 && res.data.success == true){
              if(td.isfactoryBind){
                //更新洁邦尼订单中的设备
                //this.updateOrder(imei, equipmentNo);
              }else{
                Toast.success('成功');
                //console.log(td.isfactoryBindNew);

                if(td.isfactoryBindNew != null && td.isfactoryBindNew && parameter.data.id == null){
                  //console.log("进来了吗");
                  //获取列表页对象
                  let pages = getCurrentPages();
                  console.log(pages.length);
                  let prevPage = pages[pages.length - 3];
                  console.log(prevPage);
                  prevPage.refreshListAndPage();
                  wx.navigateBack();
                }else{
                    //获取列表页对象
                    let pages = getCurrentPages();
                    let prevPage = pages[pages.length - 2];

                    //更新查询设备范围，返回列表页并刷新数据
                    if(prevPage.data.idArr.length){
                      prevPage.setData({
                        idArr: prevPage.data.idArr.concat(res.data.data)
                      })
                    }
                    prevPage.refreshListAndPage();
                    wx.navigateBack();
                }
              }

              //绑定kafka分区
              //this.bindKafka(imei);

              //关联查询字段更新到设备表
              this.updateEquipment(res.data.data.id);
 
              //同步es数据库（先判断是否修改了imei）
             let isUpdateImei=false;
             if(td.isEdit && td.editInfo.imei!=imei){
              isUpdateImei=true;
             }
             this.mongoToElastic(res.data.data.id,isUpdateImei);

              //如果是厂家从采购订单里面绑的物联网需要更新订单信息中物联网信息
              if(td.isfactoryBindNew){
                this.updateOrderIotInfo(e,parameter);
              }

              //更新物联网仓库的状态
              this.updateIotWarehouse(parameter.data.imei);

              //如果是编辑（这里的判断是重复添加的，秦海文代码）处理旧模块归属仓库问题
              if(td.isEdit){
                this.updateIotOldImeiQWarehouse(oldImeiQ);
              }

              //同步pcsql数据库
              this.syncPcsql(res.data.data.id);

            }else if(res.statusCode==202){
              Toast.fail('您操作太快了,请勿重复提交');
            }
          }).catch((error) => {
            Toast.clear();
            Toast.fail('请求数据资源服务错误');
          })

        }
      });
    });
  },

  //added by 毕研帅  2022-04-20 18:04
  //绑定完物联网后把物联网编码跟设备编码更新到订单里面，
  //这个方法只用到采购订单里面帮物联网
  updateOrderIotInfo(e,parameter){
    //绑定完设备更新采购订单里面的状态
    //先根据订单id把订单查出来
    let id = 0 ;
    let detailIndex = 0;
    if(parameter.data.id != null && parameter.data.id != ""){
      console.log("----");
        id = this.data.purchaseOrderId;
        detailIndex = this.data.detailIndex;
    }else{
        id = this.data.factoryBind.orderId;
        detailIndex = this.data.factoryBind.detailIndex;
    }

    let param={
      isAuth:false,
      className:'purchaseOrder',
      data:{
        selectFields:["id","orderNo","member","createTime","sellAmount","purchaseAmount","state","member","orderId","supplier",
        "address","businessType","orderNo","relationOrderNo","kind","salesman","detail","project","servicer","numbers"],
        id:id
      }
    }
    CommonService.goFindList(param).then(res=>{
      console.log("测试的查询订单");
      console.log(res);
      //1.修改此订单未绑定的未定设备数量，在保存采购订单的时候就把此订单下的设备数量做了统计numbers这个字段
      //2.设备绑定后更新numbers，numbers等于数据库的numbers这个字段减1
      //3.绑定设备的时候把这台设备的下标（detailIndex）传过来了,根据下标获取订单中detail的对应的对象，
      //4.获取detail对象后再更新绑定的物联网编号
      let arr = res.data.data.result[0].detail
      for(let i=0;i<arr.length;i++){
        if (detailIndex == arr[i].orderIndex){
          let detailObj = arr[i]
          detailObj.imei = e.detail.value.imei.trim();
          detailObj.equipmentNo = e.detail.value.equipmentNo.trim();
          detailObj.dataAuthority = parameter.data.dataAuthority
        }
      }

      let param = {};

      if(parameter.data.id != null && parameter.data.id != ""){
        param = {
          className:'purchaseOrder',
          data:{
            id:id,
            detail:res.data.data.result[0].detail
          }
        }
      }else{
         param = {
          className:'purchaseOrder',
          data:{
            id:id,
            numbers:res.data.data.result[0].numbers-1,
            detail:res.data.data.result[0].detail
          }
        }
      }

      CommonService.goSave(param).then(item=>{
      if (item.statusCode == 200 && item.data.success == true){
      
        //根据采购订单relationOrderNo查询租赁/销售/试机订单
        let tableName = "";
        if(this.data.businessType == 1 || this.data.businessType == 2){
          tableName="order";
        }else if(this.data.businessType == 4){
          tableName="tryOrder";
        }
        let param1={
          isAuth:false,
          className:tableName,
          data:{
            selectFields:["id","orderNo","splitDetail","type"],
            orderNo:this.data.orderNo
          }
        }

          CommonService.goFindList(param1).then(res1=>{
            console.log("查询订单");
              for(let i=0;i<res1.data.data.result[0].splitDetail.length;i++){
                let orderDetail = res1.data.data.result[0].splitDetail[i]
                console.log(orderDetail.id);
                console.log(orderDetail.index);
                if(this.data.orderDetailId == orderDetail.id && this.data.orderDetailInedx == orderDetail.index){
                  orderDetail.imei = e.detail.value.imei.trim();
                  orderDetail.equipmentNo = e.detail.value.equipmentNo.trim();
                  orderDetail.dataAuthority = parameter.data.dataAuthority
                }
              }

              let orderParam = {
                className:tableName,
                data:{
                  id:res1.data.data.result[0].id,
                  splitDetail:res1.data.data.result[0].splitDetail
                }
              }

              CommonService.goSave(orderParam).then(res=>{
              })

              //更新t_purchase_equipment表
              this.updatePurchaseEquipment(res1,res);

              if(parameter.data.id == null){
                    //  //获取列表页对象
                    let pages = getCurrentPages();
                    //console.log(pages.length);
                    let prevPage = pages[pages.length - 2];
                    //console.log(prevPage);
                    prevPage.refreshListAndPage();
                    wx.navigateBack();
              }
          })
        }
      })
    })
  },

  updatePurchaseEquipment(res1,res){
    let orderParam = {
      data:{
        orderNo:res.data.data.result[0].orderNo,
        splitDetail:res1.data.data.result[0].splitDetail
      }
    }
    CommonService.updatePurchaseEquipment(orderParam).then(res=>{

    })
  },

  //判断表单非空（涉及到数据提交，field可以在调用前去空格）
  formNotEmpty(field,messageField,messageCon){
    //field=field.trim();
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //验证imei重复
  isExist(imei){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        imei:imei,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //验证设备编码重复
  isExistNo(equipmentNo){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        equipmentNo:equipmentNo,
        selectFields: ['id'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //验证设备别名重复
  isExistAlias(alias){
    let param = {
      isAuth: false,
      className: 'equipment',
      data: {
        searchAll: true,
        equipmentAlias:alias,
        selectFields: ['id']
      }
    }
    if(this.data.memberId){
      param.data.memberId=this.data.memberId;
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param,false).then(res=>{
        if (res.data.data && res.data.data.result && res.data.data.count) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //扫码-imei
  scanCode(e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        that.setData({
          imei: res.result
        })
      }
    })
  },

  //扫码-equipmentNo
  scanEquipmentNo(e) {
    var that = this;
    wx.scanCode({
      success: (res) => {
        let equipmentNo='editInfo.equipmentNo';
        that.setData({
          [equipmentNo]:res.result
        })
      }
    })
  },

  //显示厂家选择框
  onShowFactory(){
    this.setData({
			showFactory: true
    })  

    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        level:1,
        type:2,
        selectFields:["id","name"]  
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          factoryList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏厂家选择框
  onCloseFactory(){
    this.setData({
			showFactory: false
    })
  },

  //确认厂家
  onConfirmFactory(e){
    this.setData({
      factoryId: e.detail.value.id,
      factoryName: e.detail.value.text
    })
    this.onCloseFactory();
  },

  //2023-8-15暂时改成不用这个了，后台无法维护factory_equipment_type，可维护equipmentBase
	//选择设备型号，现在新订单的厂家设备型号在factory_equipment_type表里
	//判断isfactoryBindNew（新订单进入绑设备）是否为true,如果是true，设备型号从factory_equipment_type里查，为false跟之前一样
	changeFactoryType() {
		if (this.data.isfactoryBindNew) {
			this.onShowFactoryTypeNew();
		} else {
			this.onShowFactoryType();
		}
	},

  //显示厂家设备型号选择框
  onShowFactoryType(){
    this.setData({
      showFactoryType: true
    })

    this.getFactoryType();    
  },

  //获取厂家设备型号
  getFactoryType(){
    let user=app.globalData.userInfo;

    let param = {
        isAuth: false,
        className: 'equipmentBase',
        data: {
          searchAll: true,
          factoryId: user.departObj[0].id,
          selectFields: ['id','typeCode','iconUrl','cleanArea']
        }
      }
  
      CommonService.goFindList(param).then(res=>{
        if(res.data.data && res.data.data.result && res.data.data.result.length){
          let result=res.data.data.result;
          let arr=[];
          result.forEach(item => {
            arr.push({
              text:item.typeCode,
              id:item.id,
              obj:item
            });
          });
          this.setData({
            factoryTypeList: arr
          })
        }
      }).catch((error) => {
      })
  },

  onShowFactoryTypeNew(){
    let user=app.globalData.userInfo;

    this.setData({
      showFactoryType: true
    })

    //获取厂家设备型号数据
    let parameter = {
      className: 'factoryEquipmentType',
      data: {
        isAuth:false,
        searchAll: true,
        factoryId:user.departObj[0].id,
        selectFields: ['id', 'brandId','factoryId','name',"productName"]
      }
    }
    //console.log(parameter);
    CommonService.goFindList(parameter).then(res=>{
      //console.log("res");
      //console.log(res);
      if(res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({
          factoryTypeList: arr
        })
      }
    }).catch((error) => {

    })
  },

  //隐藏厂家设备型号选择框
  onCloseFactoryType(){
    this.setData({
			showFactoryType: false
		})
  },

  //确认选择厂家设备型号
	onConfirmFactoryType(e) {
        let obj = e.detail.value.obj;
        let memberTypeNameStr = e.detail.value.text;
        
        //如果是通过订单绑的设备，memberTypeName还是用带过来的值，这里选择厂家型号不受影响
            if (this.data.isfactoryBindNew) {
                memberTypeNameStr = this.data.memberTypeName;
        }
        
            this.setData({
                equipmentBaseId: e.detail.value.id,
                equipmentBaseName: e.detail.value.text,
                memberTypeName: memberTypeNameStr,
                showFactoryType: false,
                disabled: false
            })
    
            if (obj.iconUrl) {
                this.setData({
                    headImg: obj.iconUrl,
                    showUpload: false
                })
            }
    
            if (obj.cleanArea) {
                this.setData({
                    workAmount: obj.cleanArea
                })
        }
    },

  //显示选择经销商
  onShowDealer(){
    this.setData({
			showDealer: true
    })

    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        type:7,
        selectFields:["id","name"]        
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          dealerList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏选择经销商
  onCloseDealer(){
    this.setData({
			showDealer: false
		})
  },

  //确认选择经销商
  onConfirmDealer(e){
    this.setData({
      dealerId: e.detail.value.id,
      dealerName: e.detail.value.text
    });
    this.onCloseDealer();
  },

  //显示选择客户
  onShowMember(){
    this.setData({
			showMember: true
    })

    //查询客户
    this.findMember();
  },

  //查询客户
  findMember(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        level:1,
        selectFields:['id','name'],
        complex:[{
          "or": {
            type:4,
            multiType:4
          }
        }]
      }
    }

    //客户名称模糊查询
    if(this.data.valueSearchMember){
      param.data.name='%'+this.data.valueSearchMember+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            type:list[i].type
          }
          arr.push(obj);
        }
        this.setData({
          memberList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏选择客户
  onCloseMember(){
    this.setData({
			showMember: false
		})
  },

  //确认选择客户
  onConfirmMember(e){
    this.setData({
      memberId: e.detail.value.id,
      memberName: e.detail.value.text,
      memberOfType: e.detail.value.type,
      disabled: false
    })
    this.onCloseMember();
  },

  //改变客户-重置客户型号、项目、大区、中心
  onChangeMember(){
    let centreId='editInfo.centreId';
    let centre='editInfo.centre';

    this.setData({
      memberTypeId: null,
      memberTypeStr: '',
      projectId: null,
      projectName: '',
      regionId: null,
      regionName: '',
      regionList:[],
      [centreId]:null,
      [centre]:''
    })
  },

  //显示客户设备型号选择框
  onShowUserType(){
    let user=app.globalData.userInfo;
    let memberId=null;

    if(user.isIotInstaller==true){
      memberId=this.data.memberId;
      if(!memberId){
        Toast.fail('请先选择甲方公司');
        return;
      }      
    }else{
      memberId=user.departObj[0].companyId
    }

    this.setData({
			showUserType: true
    })

    let param = {
      isAuth: false,
      className: 'equipmentMemberType',
      data: {
        searchAll: true,
        memberId: memberId,
        selectFields: ['id','name','iconUrl','cleanArea'],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{  
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });
        this.setData({
          userTypeList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏客户设备型号选择框
  onCloseUserType(){
    this.setData({
			showUserType: false
		})
  },

  //确认选择客户设备型号
  onConfirmUserType(e){
    let obj=e.detail.value.obj;

    this.setData({
      memberTypeId: e.detail.value.id,
      memberTypeStr: e.detail.value.text,
      showUserType: false
    });

    if(obj.iconUrl){
      this.setData({
        headImg: obj.iconUrl,
        showUpload:false
      })
    }

    if(obj.cleanArea){
      this.setData({
        workAmount:obj.cleanArea
      })
    }
  },

  //显示项目选择框
  onShowProject(){
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      if(this.data.memberId){
        this.setData({
          showProject: true
        })
        //获取项目数据
        this.getProjectData();
      }else{
        Toast.fail('请先选择甲方公司');
      }
    }else{
      this.setData({
        showProject: true
      })
      //获取项目数据
      this.getProjectData();
    }
  },

  //获取项目数据
  getProjectData(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        isProject:true,
        selectFields:["id","name","fid","fDepart"],
        complex:[{
          "or": {
            type:4,
            multiType:4
          }
        }],
        sort:{
          createDate:-1
        },
      }
    }

    //项目名称模糊查询
    if(this.data.valueSearchProject){
      param.data.name='%'+this.data.valueSearchProject+'%'
    }

    //如果是安装人员
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      param.nbl=Base64.encode(util.timeFormatDay(new Date()));
      param.data.companyId=this.data.memberId;
    }

    //如果有大区
    // if(this.data.regionId){
    //   param.data.fid=this.data.regionId;
    // }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            fid:list[i].fid,
            //上级机构名称
            fName: list[i].fDepart.length ?  list[i].fDepart[0].name : null
          }
          arr.push(obj);
        }
        this.setData({
          projectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏项目选择框
  onCloseProject(){
    this.setData({
            showProject: false
		})
  },

  //确认项目
  onConfirmProject(e){
    this.setData({
      projectId: e.detail.value.id,
      projectName: e.detail.value.text,
      disabled: false
    })

    //自动选择大区
    if(!this.data.regionId){
      this.autoSelectRegion(e.detail.value.fid);
    }

    this.onCloseProject();
  },

  //自动选择大区
  autoSelectRegion(fid){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        searchAll:true,
        //isRegion:true,
        id:fid,
        selectFields:["id","name"]
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          regionId: result.id,
          regionName: result.name
        })
      }
    }).catch((error) => {
    })
  },  

  //显示上传图片组件
  onShowUpload(){
    this.setData({
			showUpload: true
		})
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgArr=data.detail;
    if(imgArr.length){
      this.setData({
        headImg: imgArr[0]
      })
    }
  },

  //跳转添加项目
  goToAddDepart(){
    let user=app.globalData.userInfo;
    let companyId=null,
        companyName='';

    if(user.departObj[0].type==4){
      companyId=user.depart;
      companyName=user.departObj[0].name;
    }else{
      if(this.data.memberId){
        companyId=this.data.memberId;
        companyName=this.data.memberName;
      }else{
        Toast.fail('请先选择甲方公司');
        return;
      }
    }  

    let obj={
      companyId: companyId,
      companyName: companyName,
      regionId: this.data.regionId,
      rid: this.data.regionId,
      regionName: this.data.regionName
    }

    wx.navigateTo({
      url: "/pages/departAdd/departAdd?paramObj="+JSON.stringify(obj)
    }) 
  },

  //显示选择清洁单位
  onShowWorkUnit(){
    this.setData({
      showWorkUnit: true,
      workUnitMessage:'',
      disabled:true
    })
  },

  //隐藏选择清洁单位
  onCloseWorkUnit(){
    this.setData({
			showWorkUnit: false
    })
  },

  //确认选择清洁单位
  onConfirmWorkUnit(e){
    this.setData({
      workUnit: e.detail.value.workUnit,
      workUnitStr: e.detail.value.text,
      disabled:false
    })
    this.onCloseWorkUnit();
  },

  //显示选择充电方式
  onShowCharge(){
    this.setData({
			showCharge: true
    })
  },

  //隐藏选择充电方式
  onCloseCharge(){
    this.setData({
			showCharge: false
    })
  },

  //确认选择充电方式
  onConfirmCharge(e){
    this.setData({
      chargeId: e.detail.value.id,
      chargeName: e.detail.value.text
    })
    this.onCloseCharge();
  },

  //更新洁邦尼订单中的设备
  updateOrder(imei,equipmentNo){
    let param={
      className:'deliverGoodsItems',
      data:{
        id: this.data.factoryBind.id,
        imei: imei,
        equipmentNo: equipmentNo
      }
    }

    CommonService.goSave(param).then(res=>{
      if (res.statusCode == 200 && res.data.success == true){
        if(this.data.isEdit){
          Toast.success('成功');
          //返回
          this.backAndRefresh();
        }else{
          //更新洁邦尼订单的状态
          this.updateOrderState();
        }
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },  

  //更新洁邦尼订单的状态
  updateOrderState(){
    let param={
      className:'deliverGoods',
      data:{
        filter: {
          id:this.data.factoryBind.orderId
        },
        update: {
          set: {
            numbers:this.data.factoryBind.numbers-1  
          }
        }
      }
    }

    CommonService.goUpdate(param).then(res=>{
      if (res.statusCode == 200 && res.data.code == 200){
        Toast.success('成功');
        //返回
        this.backAndRefresh();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 3];
    prevPage.refreshListAndPage();
    wx.navigateBack({
      delta: 2
    })
  },

  //查询合伙人
  findPartner(depart){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        id:depart,
        selectFields:["id","partnerId"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data) {
          let result=res.data.data.result[0];
          if(result.partnerId){
            resolve(result.partnerId);
          }else{
            resolve(null);
          }
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });
  },

  //绑定kafka分区
  bindKafka(imei){
    let param={
      imei:imei
    }
    CommonService.bindPartition(param).then(res=>{
    }).catch((error) => {
    })
  },

  //根据id查询depart名称
  getDepartName(id){
    let param={
      isAuth:false,
      className:'depart',
      data:{
        id:id,
        selectFields:["id","name"]
      }
    }

    return new Promise((resolve, reject) => {
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.result.length) {
          let result=res.data.data.result[0];
            resolve(result.name);
        } else {
          resolve(null);
        }
      }).catch((error) => {
        resolve(null);
      })
    });
  },

  //查询设备一级分类
  findEquipmentCategory(){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: 1,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        this.setData({
          typeOne: cateArr
        })
        //查询子分类
        this.findChildren(result[0].id);
      }
    }).catch((error) => {
    })
  },

  //查询子分类
  findChildren(fid){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: fid,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      let typeOne=this.data.typeOne;
      //处理分类数据格式
      let typeList=[{
        values: typeOne,
        className: 'column1'
      }]

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        typeList.push({
          values: cateArr,
          className: 'column2'
        });
      }else{
        typeList.push({
          values: [],
          className: 'column2'
        });
      }

      this.setData({
        typeList: typeList
      })
    }).catch((error) => {
    })
  },

  //显示设备类型选择框
  onShowType(){
    this.setData({
			showType: true
    })
    //查询一级
    this.findEquipmentCategory();
  },

  //隐藏设备类型选择框
  onCloseType(){
    this.setData({
			showType: false
    })
  },

  //选择设备类型
  onChangeType(event) {
    const { picker, value, index } = event.detail;
    let arr=picker.getValues();
    this.findChildren(arr[0].id);
  },

  //确认设备类型
  onConfirmType(e){
    let arr=e.detail.value;
    let idArr=[],nameArr=[];

    arr.forEach(item => {
      if(item){
        idArr.push(item.id);
        nameArr.push(item.text);
      }
		});

    this.setData({
      typeIds: idArr,
      typeNames: nameArr.join(' - '),
      disabled: false
    })
    this.onCloseType();
  },

  //显示保洁供应方
  onShowCleaningSupplier() {
    this.setData({
      showCleaningSupplier: true
    })
    //查询保洁供应方
    this.getCleaningSupplier();
  },

  //查询保洁供应方
  getCleaningSupplier() {
    let param={
      isAuth:false,
      className:'depart',
      data:{
        searchAll:true,
        type:4,
        level:1,
        selectFields:["id","name"]
      }
    }

    //名称模糊查询
    if(this.data.valueSearchCleaning){
      param.data.name='%'+this.data.valueSearchCleaning+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          cleaningSupplierList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方
  onCloseCleaningSupplier() {
    this.setData({
      showCleaningSupplier: false
    })
  },

  //确认保洁供应方
  onConfirmCleaningSupplier(e){
    this.setData({
      cleaningSupplierId: e.detail.value.id,
      cleaningSupplierName: e.detail.value.text
    })
    this.onCloseCleaningSupplier();
  },

  //选择保洁供应方-搜索
  onChangeCleaning(e){
    this.setData({
      valueSearchCleaning: e.detail
    })

    //获取保洁供应方数据
    this.getCleaningSupplier();
  },

  //显示保洁供应方项目
  onShowCleaningSupplierProject() {
    if(this.data.cleaningSupplierId){
      this.setData({
        showCleaningSupplierProject: true
      })
      //查询保洁供应方项目
      this.getCleaningSupplierProject();
    }else{
      Toast.fail('请先选择保洁供应方');
    }
  },

  //查询保洁供应方项目
  getCleaningSupplierProject() {
    let param={
      isAuth:false,
      className:'depart',
      data:{
        searchAll:true,
        companyId:this.data.cleaningSupplierId,
        level:{"!=":1},
        selectFields:["id","name"]
      }
    }

    //名称模糊查询
    if(this.data.valueSearchCleaningProject){
      param.data.name='%'+this.data.valueSearchCleaningProject+'%'
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id
          }
          arr.push(obj);
        }
        this.setData({
          cleaningSupplierProjectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏保洁供应方项目
  onCloseCleaningSupplierProject() {
    this.setData({
      showCleaningSupplierProject: false
    })
  },

  //确认保洁供应方项目
  onConfirmCleaningSupplierProject(e){
    this.setData({
      cleaningSupplierProjectId: e.detail.value.id,
      cleaningSupplierProjectName: e.detail.value.text
    })
    this.onCloseCleaningSupplierProject();
  },

  //选择保洁供应方项目-搜索
  onChangeCleaningProject(e){
    this.setData({
      valueSearchCleaningProject: e.detail
    })

    //获取保洁供应方项目数据
    this.getCleaningSupplierProject();
  },

  //选择客户-搜索
  onChangeMemberName(e){
    this.setData({
      valueSearchMember: e.detail
    })

    //查询客户
    this.findMember();
  },

  //选择项目-搜索
  onChangeProjectName(e){
    this.setData({
      valueSearchProject: e.detail
    })

    //获取项目数据
    this.getProjectData();
  },  

  //所有权
  onChangeOwner(event) {
    this.setData({
      owner: event.detail,
    })
  },

  //修改权
  onChangeEditer(event) {
    this.setData({
      editer: event.detail,
    })
  },

  //改变保洁供应方-重置供方项目
  onChangeCleaningSupplier(){
    this.setData({
      cleaningSupplierProjectId: null,
      cleaningSupplierProjectName: ''
    })
  },

  //显示大区选择框
  onShowRegion(){
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      if(this.data.memberId){
        this.setData({
          showRegion: true
        })
        //获取大区数据
        this.getRegionData();
      }else{
        Toast.fail('请先选择甲方公司');
      }
    }else{
      this.setData({
        showRegion: true
      })
      //获取大区数据
      this.getRegionData();
    }
  },

  //获取大区数据
  getRegionData(){
    let param={
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,
        isRegion:true,
        selectFields:["id","name","level"]
      }
    }

    //大区名称模糊查询
    if(this.data.valueSearchRegion){
      param.data.name='%'+this.data.valueSearchRegion+'%'
    }

    //如果是安装人员
    let user=app.globalData.userInfo;
    if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
      param.data.nbl=Base64.encode(util.timeFormatDay(new Date()));
      param.data.companyId=this.data.memberId;
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data){
        let list=res.data.data.result;
        let arr=[];
        for(let i=0;i<list.length;i++){
          let obj={
            text:list[i].name,
            id:list[i].id,
            obj:list[i]
          }
          arr.push(obj);
        }
        this.setData({
          regionList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏大区选择框
  onCloseRegion(){
    this.setData({
      showRegion: false
		})
  },

  //确认大区
  onConfirmRegion(e){
    this.setData({
      regionId: e.detail.value.id,
      regionName: e.detail.value.text,
      regionObj:e.detail.value.obj
    })
    this.onCloseRegion();
  },

  //清除大区选择
  onCancelRegion(){
    this.setData({
      regionId: null,
      regionName: ''
    })
    this.onCloseRegion();
  },

  //改变大区-重置项目
  onChangeRegion(){
    this.setData({
      projectId: null,
      projectName: ''
    })
  },

  //关联查询字段更新到设备表
  updateEquipment(id){
    let param={
      equipmentId:id
    }
    CommonService.updateEquipmentAll(param).then(res=>{
    }).catch((error) => {
    })
  },

  //同步es
  mongoToElastic(id,isUpdateImei){
    let param={
      equipmentId: id,
      isUpdateImei: isUpdateImei
    }
    CommonService.mongoToElastic(param).then(res=>{
    }).catch((error) => {
    })
  },

  //查询项目fid（从订单来的，需要根据项目查询大区）
  getProjectFid(projectId){
    let param = {
      isAuth: false,
      className: 'depart',
      data: {
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        id: projectId,
        selectFields: ['id','name','fid']
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.autoSelectRegion(result.fid);
      }
    }).catch((error) => {
    })
  },

  //根据设备型号查询相关信息
  findFactoryType(){
    let user=app.globalData.userInfo;
    let memberTypeName=this.data.memberTypeName;
    let factoryId=user.departObj[0].id;

    let param = {
      isAuth: false,
      className: 'equipmentBase',
      data: {
        searchAll: true,
        factoryId: factoryId,
        typeCode: memberTypeName,
        selectFields: ["id","typeCode", "iconUrl","cleanArea"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{  
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          equipmentBaseId: result.id,
          equipmentBaseName: result.typeCode,
          headImg: result.iconUrl,
          showUpload:false,
          workAmount:result.cleanArea
        })
      }
    }).catch((error) => {
    })
  },
  
  //切换显示equipmentNo输入框
  onChangeNo({detail}) {
    this.setData({
      showNo: detail
    })
  },

  //显示业务类型选择框
  onShowBusinessType(){
    this.setData({
			showBusinessType: true
    })
  },

  //隐藏业务类型选择框
  onCloseBusinessType(){
    this.setData({
      showBusinessType: false
    })
  },

  //确认业务类型
  onConfirmBusinessType(e){
    let businessTypeName='editInfo.businessTypeName';
    this.setData({
      businessType: e.detail.value.id,
      [businessTypeName]: e.detail.value.text,
      disabled: false
    })
    this.onCloseBusinessType();
  },

  //跳转添加厂家型号
  goToAddFactoryType(){
    wx.navigateTo({
        url: "/packageA/pages/factoryTypeAdd/factoryTypeAdd"
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })
    
    //中心
    if(field=='centre'){
      let user=app.globalData.userInfo;
      if(user.isIotInstaller==true || user.departObj[0].type==7 || user.departObj[0].type==1){
        if(!this.data.memberId){
          Toast.fail('请先选择甲方公司');
          return;
        }
      }

      this.setData({
        selectTitle: '中心',
        showSelectSearch:true
      })
      this.getCentreList();
    } 
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: ''
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //中心
    if(selectField=='centre'){
        id='editInfo.centreId';
        name='editInfo.centre';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;    

    //中心
    if(selectField=='centre'){
      id='editInfo.centreId';
      name='editInfo.centre';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //中心
    if(selectField=='centre'){
      this.getCentreList();
    }
  },

  //查询中心
  getCentreList(){
    let param = {
      isAuth:true,
      className:'depart',
      data:{
        searchAll:true,  
        selectFields:["id","name"],
        companyId:this.data.memberId,
        id:{
          '!=':this.data.memberId
        }
      }
    }

    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:item
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //更新物联网仓库的状态
  updateIotWarehouse(imei){
    let param = {
      isAuth: false,
      className: 'imeiWarehouseInFactoryS',
      data: {
        imei: imei,
        state:0,//秦海文修改，不管仓库功能怎么修改，只能找state=0的数据，同一个imei可以查询多条，但是状态为0的只能为1条
        selectFields: ['id','imei',"mId"],
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    //查询是否在仓库中
    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        let param2={
          className:'imeiWarehouseInFactoryS',
          data:{
            id: result.id,
            state: 1
          }
        }

        //更新状态
        CommonService.goSave(param2).then(res=>{
        }).catch((error) => {
        })
      }
    })
  },

  //秦海文2023年2月17日添加/////////////////////////////////////////////////////////////////////////////////////////////////////////
  //更换下来的旧模块归属仓库问题
  updateIotOldImeiQWarehouse(imei){
    let oldParam = {
      isAuth: false,
      className: 'imeiWarehouseInFactoryS',
      data: {
        imei: imei,
        state:1,////秦海文修改，不管仓库功能怎么修改，只能找state=1的数据，同一个imei可以查询多条，但是状态为1的只能为1条
        nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }
    //查询旧模块是否在仓库中
    CommonService.goFindList(oldParam).then(res => {
        //如果旧模块在仓库中
        if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let resultOld=res.data.data.result[0];
        console.log(resultOld.mId);
        //拿到主表ID之后查询主表，寻找旧模块所在人员是否是当前登录人
        let userParam={
            className:'imeiWarehouseInFactoryM',
            data:{
            id:resultOld.mId
            }
        }
        CommonService.goFindList(userParam).then(res => {
            console.log("主表数据ID输出");
            //拿到主表id
            console.log(res.data.data.result[0].collectUserId);
            //如果当前登陆人ID和旧模块之前拥有者ID相同
            if(res.data.data.result[0].collectUserId===app.globalData.userInfo.id){
            //模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有 
            let oldImeiParam={
                className:'imeiWarehouseInFactoryS',
                data:{
                id:resultOld.id,
                state:2
                }
            }
            //更新状态
            CommonService.goSave(oldImeiParam).then(res=>{
            }).catch((error) => {
            })
            }else{//如果当前登陆人ID和旧模块之前拥有者ID不同
            //首先将旧模块的状态变成3
            let oldImeiParam={
                className:'imeiWarehouseInFactoryS',
                data:{
                id:resultOld.id,
                state:3
                }
            }
            //更新状态
            CommonService.goSave(oldImeiParam).then(res=>{
            }).catch((error) => {
            })
            //再将resultOld的数据复制写入
            let newObjResult={
                className:'imeiWarehouseInFactoryS',
                data:{
                imei:resultOld.imei,//物联网编码
                num:1,//数量
                state:4,//模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有 
                sId:resultOld.id,//关联下，子表关联子表
                userId:app.globalData.userInfo.id,//操作者ID
                }
            }
            //写入数据
            CommonService.goSave(newObjResult).then(res=>{
            }).catch((error) => {
            })
            }
        })


        }else{
        //如果旧模块不在仓库中
        let newObjResult={
            className:'imeiWarehouseInFactoryS',
            data:{
            imei:imei,//物联网编码
            num:1,//数量
            state:4,//模块安装状态为2  0未安装  1已安装  2故障被本人换  3故障被他人换 数据条目中有用户ID 状态   4 为 故障持有 
            userId:app.globalData.userInfo.id,//操作者ID
            }
        }
        //写入数据
        CommonService.goSave(newObjResult).then(res=>{
        }).catch((error) => {
        })       
        }
    }).catch((error) => {
    })
   },
  //秦海文添加结束////////////////////////////////////////////////////////////////////////////////////////////////////////////////  

  //同步pcsql数据库
  syncPcsql(id){
    let param={
      id: id
    }
    CommonService.syncEquipment(param).then(res=>{
    }).catch((error) => {
    })
  },

  //天骏小程序，客户项目大区型号等初始化值
  initProjectInfo(){
    this.setData({
        memberId:  1806,
        memberName: '天骏智慧清洁服务平台',
        projectId: 1806,
        projectName: '天骏智慧清洁服务平台',
        regionId: 1806,
        region: '天骏智慧清洁服务平台',
        regionName: '天骏智慧清洁服务平台',       
        memberTypeName: '天骏设备', 
        memberTypeStr: '天骏设备',
        equipmentBaseName: '天骏设备'
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   *
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})